from dataclasses import dataclass
from typing import List
import json
import os
import hashlib
from pathlib import Path

@dataclass
class VersionInfo:
    id: int                     # 序号
    name: str                   # 版本名称
    vendor: str                 # 设备厂商
    file_type: str             # 文件类型（版本文件/补丁文件）
    device_models: List[str]    # 支持的设备型号
    checksum: str              # 校验码
    file_path: str             # 文件路径
    description: str           # 描述信息

class VersionManager:
    def __init__(self):
        self.config_dir = Path.home() / '.a-terminal'
        self.config_file = self.config_dir / 'versions.json'
        self._ensure_config_dir()
        self.versions = self._load_versions()

    def _ensure_config_dir(self):
        """确保配置目录存在"""
        if not self.config_dir.exists():
            self.config_dir.mkdir(parents=True)
        if not self.config_file.exists():
            self._save_versions([])

    def _load_versions(self) -> List[VersionInfo]:
        """加载版本信息"""
        try:
            with open(self.config_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
                return [VersionInfo(**item) for item in data]
        except Exception:
            return []

    def _save_versions(self, versions: List[VersionInfo]):
        """保存版本信息"""
        data = [{
            'id': v.id,
            'name': v.name,
            'vendor': v.vendor,
            'file_type': v.file_type,
            'device_models': v.device_models,
            'checksum': v.checksum,
            'file_path': v.file_path,
            'description': v.description
        } for v in versions]
        
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    def add_version(self, version: VersionInfo):
        """添加新版本"""
        if not version.id:
            version.id = self._generate_next_id()
        self.versions.append(version)
        self._save_versions(self.versions)

    def remove_version(self, version_id: int):
        """删除版本"""
        self.versions = [v for v in self.versions if v.id != version_id]
        self._save_versions(self.versions)

    def update_version(self, version: VersionInfo):
        """更新版本信息"""
        for i, v in enumerate(self.versions):
            if v.id == version.id:
                self.versions[i] = version
                break
        self._save_versions(self.versions)

    def get_all_versions(self) -> List[VersionInfo]:
        """获取所有版本信息"""
        return self.versions

    def get_version(self, version_id: int) -> VersionInfo:
        """获取指定版本信息"""
        for version in self.versions:
            if version.id == version_id:
                return version
        return None

    def _generate_next_id(self) -> int:
        """生成下一个版本ID"""
        if not self.versions:
            return 1
        return max(v.id for v in self.versions) + 1

    @staticmethod
    def calculate_checksum(file_path: str) -> str:
        """计算文件校验码"""
        if not os.path.exists(file_path):
            return ""
        
        md5_hash = hashlib.md5()
        with open(file_path, 'rb') as f:
            for byte_block in iter(lambda: f.read(4096), b""):
                md5_hash.update(byte_block)
        return md5_hash.hexdigest()